package trans.service;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.time.DateFormatUtils;
import org.hibernate.Criteria;
import org.hibernate.criterion.Restrictions;

import trans.model.Gatway;
import trans.support.Constants;
import trans.utils.HibernateUtil;

public class GatwayDAO {
	
	@SuppressWarnings("unchecked")
	public static boolean saveGatway(Gatway gatway) throws Exception{
		List<Gatway> exsitGatway = HibernateUtil.getSession().createCriteria(Gatway.class)
		.add( Restrictions.eq(Gatway.PROP_NAME, gatway.getName())).list();
		if(exsitGatway.isEmpty() == false){
			return false;
		}
		gatway.setStatus(Constants.STATUS_ENABLE);
		gatway.setNativeIndex(0);
		Integer currentMonth = Integer.parseInt(DateFormatUtils.format(new Date(), "M"));
		gatway.setNativeMonth(currentMonth);
		HibernateUtil.saveOrUpdate(gatway);
		return true;
	}
	
	public static void updateGatwayStatus(Integer id,Integer status){
		Gatway	gatway = 
			(Gatway) HibernateUtil.get(Gatway.class, id);
		gatway.setStatus(status);
		HibernateUtil.saveOrUpdate(gatway);
	}
	
	@SuppressWarnings("unchecked")
	public static List<Gatway> getAllGatway(){
		Criteria cri =  HibernateUtil.getSession().createCriteria(Gatway.class);
		cri.add(Restrictions.eq(Gatway.PROP_STATUS, Constants.STATUS_ENABLE));
		return cri.list();
	}
	
	@SuppressWarnings("unchecked")
	public static List<Gatway> getEnableGatway() throws Exception{
		return  HibernateUtil.getSession().createCriteria(Gatway.class)
		    .add( Restrictions.eq(Gatway.PROP_STATUS, Constants.STATUS_ENABLE))
		    .list();
	}
}
